﻿using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization.Json;
using System.Text;
using System.Xml.Linq;
using System.IO;

namespace Toybox.CookieGetterSharp.SQLite
{
  /// <summary>
  /// GoogleChromeのプロファイル
  /// </summary>
  class GoogleChromeProfile
  {
    /// <summary>
    /// GoogleChromeProfileのコンストラクタ
    /// </summary>
    public GoogleChromeProfile()
    {
      Path = @"Default";
    }

    /// <summary>
    /// プロファイル名
    /// </summary>
    public string Name { get; set; }

    /// <summary>
    /// プロファイルパス
    /// </summary>
    public string Path { get; set; }

    /// <summary>
    /// デフォルトプロファイルの取得
    /// </summary>
    /// <param name="path"></param>
    /// <param name="file"></param>
    /// <returns></returns>
    public static GoogleChromeProfile GetDefaultProfile(string path, string file)
    {
      foreach (var profile in GetProfiles(path, file))
      {
        if (profile.Path == @"Default") return profile;
      }

      return null;
    }

    /// <summary>
    /// すべてのプロファイル取得
    /// </summary>
    /// <param name="path"></param>
    /// <param name="file"></param>
    /// <returns></returns>
    public static GoogleChromeProfile[] GetProfiles(string path, string file)
    {
      string localstate = System.IO.Path.Combine(path, file);

      var results = new List<GoogleChromeProfile>();

      if (System.IO.File.Exists(localstate))
      {
        var json = File.ReadAllText(localstate);
        using (var jr = JsonReaderWriterFactory.CreateJsonReader(Encoding.UTF8.GetBytes(json), System.Xml.XmlDictionaryReaderQuotas.Max))
        {
          XElement xml = XElement.Load(jr);
          var nodes = ((XElement)((XElement)xml.Nodes().First((n) => ((XElement)n).Name == "profile")).FirstNode).Nodes();

          foreach (XElement one in nodes)
          {
            var profile = new GoogleChromeProfile();

            foreach (XAttribute xa in one.Attributes())
            {
              if (xa.Name == "item") profile.Path = xa.Value;
            }

            foreach (XElement element in one.Nodes())
            {
              if (element.Name == "name") profile.Name = element.Value;
            }

            results.Add(profile);
          }
        }
      }

      return results.ToArray();
    }
  }
}